﻿'use strict';

// todoPage controller
app.controller('otherWarehousing', ['$stateParams','$state','$filter','$window','$http','$scope','$modal','toaster','$log', function($stateParams,$state,$filter,$window,$http,$scope,$modal,toaster,$log) {
    function inIt(){
        getSelect();
        if($stateParams.docId===null){
            getList();
        }else if($stateParams.docId==="new"){
            $scope.warehouseJump();
        }else{
            toaster.getInfo('/a_yongan/single/othergoodin/'+$stateParams.docId,null).then(function(data){
                if(data && data.data && data.data.data){
                    makeData([data.data.data],true);
                }
            });

        }
    }
    $scope.canEdit = false;
    $scope.goods=[];//定义数组
    $scope.lists = [""];
    $scope.mylabel = $scope.lists[0];//默认数组第一个作为option的值
    $scope.rklx = [];
    $scope.rklxlabel = $scope.rklx[0];//默认数组第一个作为option的值
    function getSelect(){
        toaster.getInfo('/a_yongan/list/allselect',null).then(function(data){
            if(data && data.data && data.data.data){
                $scope.rklx = data.data.data.allSelectRklx.split(";");
            }
        });
        toaster.getInfo('/a_yongan/selectlist/warehouse',null).then(function(data){
            if(data && data.data && data.data.data){
                data.data.data.forEach(function(item){
                    $scope.lists.push(item.name);
                });
            }
        });
    }
    //删除一行
    $scope.dele =function($index){
        $scope.goods.splice($index,1);
    };
    //添加的方法
    $scope.addRows=function(){
        var id = new Date().getTime();
        var go = {
            "flag":false,
            "otherGoodInDetailsId":id,
            "otherGoodInDetailsHpbm":"",
            "otherGoodInDetailsHpmc":"",
            "otherGoodInDetailsGgxh":"",
            "otherGoodInDetailsHpdw":"",
            "otherGoodInDetailsHpsl":"",
            "otherGoodInDetailsHpdj":"",
            "otherGoodInDetailsHpzje":"",
            "otherGoodInDetailsDhrq":"",
            "otherGoodInDetailsBz":""
        }
        $scope.goods.push(go);
    };
    function objToGo(obj,index){
        $scope.goods[index].otherGoodInDetailsHpbm=obj.id;
        $scope.goods[index] .otherGoodInDetailsHpmc=obj.name;
        $scope.goods[index].otherGoodInDetailsGgxh=obj.hpxh;
        $scope.goods[index].otherGoodInDetailsHpdw=obj.dw;
        $scope.goods[index].otherGoodInDetailsHpdj=obj.dj;
        $scope.goods[index].otherGoodInDetailsHpzje=parseInt($("#"+$scope.goods[index].otherGoodInDetailsId+"otherGoodInDetailsHpsl").val())*parseFloat(obj.dj);
    }
    $scope.detailsInput = {
        sl:function(index){
            var sl = $("#"+$scope.goods[index].otherGoodInDetailsId+"otherGoodInDetailsHpsl").val();
            var dj = $scope.goods[index].otherGoodInDetailsHpdj;
            $scope.goods[index].otherGoodInDetailsHpsl = sl;
            if(dj===""){
                showMessage('warning','',"货品信息不能为空！");
                return false;
            }
            $scope.goods[index].otherGoodInDetailsHpzje = parseFloat(dj)*parseInt(sl);
        },
        bz:function(index){
            $scope.goods[index].otherGoodInDetailsBz = $("#"+$scope.goods[index].otherGoodInDetailsId+"otherGoodInDetailsBz").val();
        }
    };
    //改变每行chekbox的状态
    $scope.ck = function($index){
        $scope.goods[$index].flag=!$scope.goods[$index].flag
    }
    //批量删除
    $scope.plsc = function(){
    //反着遍历
        for (var i = $scope.goods.length-1;i>=0;i--) {
            if ($scope.goods[i].flag) {
                $scope.goods.splice(i,1);
            }
        }
    }
    //全选
    var qq = true;
    $scope.qx = function(){
    //获取属性
        var ck = $("input[name=ck]")
        for (var i=0;i<ck.length;i++) {
            ck[i].checked=qq;
            //给每个数组中的ck赋值
            $scope.goods[i].flag=qq;
        }
        qq=!qq;
    };
    function addDo(type){
        var notesdata = {};
        if($scope.canEdit){
            $scope.goods.forEach(function(item){
                item.otherGoodInDetailsDhrq=new Date($("#"+item.otherGoodInDetailsId+"otherGoodInDetailsDhrq").val()).getTime();
            });
            if(!$scope.row.otherGoodInId){
                notesdata = {
                    "otherGoodInId":"",
                    //"qy":$("#qy").prop("checked"),
                    "zdr":$scope.app.userName,
                    "zdrId":$scope.app.userId,
                    "otherGoodInDh":$("#otherGoodInDh").val(),
                    "otherGoodInShr":$("#otherGoodInShr").val(),
                    "otherGoodInRklx":$scope.rklx[$("#otherGoodInRklx").val()],
                    "otherGoodInShck":$scope.lists[$("#otherGoodInShck").val()],
                    "otherGoodInGys":$("#otherGoodInGys").val(),
                    "otherGoodInLxr":$("#otherGoodInLxr").val(),
                    "otherGoodInLxdh":$("#otherGoodInLxdh").val(),
                    "otherGoodInBz":$("#otherGoodInBz").val(),
                    "details":$scope.goods
                }
            }else{
                notesdata = {
                    "otherGoodInId":$scope.row.otherGoodInId,
                    //"qy":$("#qy").prop("checked"),
                    "otherGoodInDh":$("#otherGoodInDh").val(),
                    "otherGoodInShr":$("#otherGoodInShr").val(),
                    "otherGoodInRklx":$scope.rklx[$("#otherGoodInRklx").val()],
                    "otherGoodInShck":$scope.lists[$("#otherGoodInShck").val()],
                    "otherGoodInGys":$("#otherGoodInGys").val(),
                    "otherGoodInLxr":$("#otherGoodInLxr").val(),
                    "otherGoodInLxdh":$("#otherGoodInLxdh").val(),
                    "otherGoodInBz":$("#otherGoodInBz").val(),
                    "details":$scope.goods
                }
            }
        }else{
            $scope.goods.forEach(function(item){
                item.otherGoodInDetailsDhrq=new Date(item.otherGoodInDetailsDhrq).getTime();
            });
            $scope.row.createTime = new Date($scope.row.createTime).getTime();
            notesdata = $scope.row;
        }
        var info="";
        toaster.postInfo('/a_yongan/add/othergoodin',notesdata).then(function(data){
            if(data && data.data && data.data.success && data.data.data){
                if(type!=='bc'){
                    var params = {
                        "id":data.data.data.personalWorkDocId,
                        "type":1,
                        "flow":"othergoodin",
                        "data":data.data.data
                    };
                    if(type==="th"){
                        params.type = -1;
                    }
                    toaster.postInfo('/a_yongan/workflow/othergoodin',params).then(function(data){
                        if(data && data.data && data.data.success){
                            showMessage('seccess','','操作成功！');
                            if($scope.app.power.powerOthergoodIn){
                                $scope.warehouseAdd = !($scope.warehouseAdd);
                                $scope.warehouseList = !($scope.warehouseList);
                                getList();
                            }else{
                                alert('提交成功，即将返回待办界面！');
                                $state.go('app.todoPage');
                            }
                            return info;
                        }else{
                            showMessage('warning','','操作失败！');
                            info = "请求错误！";
                        }
                    });
                }else{
                    showMessage('seccess','','保存成功！');
                    $scope.warehouseAdd = !($scope.warehouseAdd);
                    $scope.warehouseList = !($scope.warehouseList);
                    getList();
                    return info;
                }
                //return info;
            }else{
                showMessage('warning','','保存失败！');
                info = "请求错误！";
            }
        });
        return info;
    }
    $scope.title = {
        title:'其他入库单列表',
        addTitle:'其他入库单信息'
    };
    $scope.toaster = {
        type: 'warning',
        title: '提示：',
        text: '内容不能为空！'
    };
    $scope.SelectPrice = function(index,bm){
        if(bm.otherGoodInDetailsHpbm && bm.otherGoodInDetailsHpbm!==""){
            toaster.getInfo('/a_yongan/list/goodsprice/'+bm.otherGoodInDetailsHpbm,null).then(function(data){
                if(data && data.data && data.data.data){
                    console.log(data.data.data);
                    var modalInstance = $modal.open({
                        templateUrl: 'selectPrice.html',
                        controller: 'selectPriceCtrl',
                        size: 'sm',
                        resolve: {
                            items: function () {
                                return data.data.data;
                            }
                        }
                    });
                    modalInstance.result.then(function (selectedItem) {
                        $scope.goods[index].otherGoodInDetailsHpdj = selectedItem;
                        $scope.goods[index].otherGoodInDetailsHpzje = parseFloat(selectedItem)*parseFloat($scope.goods[index].otherGoodInDetailsHpsl);
                        showMessage('success','','选择成功！');
                    }, function () {
                        $log.info('Modal dismissed at: ' + new Date());
                    });
                }
            });
        }else{
            showMessage('warning','','货品编码不能为空！');
        }
    };
    function makeData(data,single){
        data.forEach(function (item) {
            item.createTime = $filter("date")(item.createTime, "yyyy/MM/dd");
            item.details.forEach(function(detail){
                detail.otherGoodInDetailsDhrq = $filter("date")(detail.otherGoodInDetailsDhrq, "yyyy/MM/dd");
            });
            if(item.state.indexOf("办结")>=0){
                item.status1 = 'label bg-danger';
            }else{
                item.status1 = 'label bg-info';
            }
        })
        if(single){
            $scope.showInfo(data[0]);
        }else{
            $scope.saveDate = data;
        }
    }
    function getList(){
        toaster.getInfo('/a_yongan/list/othergoodin',null).then(function(data){
            if(data && data.data && data.data.data){
                makeData(data.data.data);
            }
        });
    }
    getList();
    $scope.pop = function(){
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    };
    function showMessage(type,title,text){
        $scope.toaster.type = type;
        $scope.toaster.text = text;
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    }
    function checkItems(){
        var items = ['otherGoodInShr','otherGoodInGys'];
        var itemsValue = ['收货人','供应商'];
        for(var i=0;i<items.length;i++){
            if($('#'+items[i]+'').val()===''){
                $('#'+items[i]+'').focus();
                showMessage('warning','',itemsValue[i]+"不能为空！");
                return false;
            }
        }
        return true;
    }
    $scope.message = '';
    $scope.saveInfo = function (size,msg) {
        var type='';
        if(msg==='th'){
            type = '退回';
        }else if(msg==='bc'){
            type = '保存';
        }else if(msg==='tj'){
            type ='提交';
        }else{
            return;
        }
        $scope.message = '是否确定'+type+'？';
        if(!checkItems()){
            return;
        }
        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            size: size,
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            var info = addDo(msg);
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.isshow=true;
    $scope.warehouseAdd = false;
    $scope.warehouseList = true;
    $scope.warehouseJump = function(ts) {
        if(ts!=='back'){
            $scope.canEdit = true;
            $scope.mylabel = $scope.lists[0];
            $scope.rklxlabel = $scope.rklx[0];
            $scope.row = {};
            $scope.goods=[];
            $scope.showFiles = [];
            $scope.row = {
                'createTime':$filter("date")(new Date(), "yyyy/MM/dd"),
                'zdr':$scope.app.userName,
                'upDateUserId':"new",
                'otherGoodInDh':'QTRK'+$filter("date")(new Date(), "yyyyMMddHHmmss")
            };
        }else{
            $scope.canEdit = false;
            getList();
        }
        $scope.warehouseAdd = !($scope.warehouseAdd);
        $scope.warehouseList = !($scope.warehouseList);
    };
    $scope.row = {};
    $scope.columns = [
        {
            title:'创建时间',
            show:true
        },
        {
            title:'单据编号',
            show:true
        },
        {
            title:'收货仓库',
            show:true
        },
        {
            title:'收货人',
            show:true
        },
        {
            title:'供应商',
            show:true
        },
        {
            title:'单据状态',
            show:true
        }
    ];
    $scope.saveDate=[];
    $scope.showInfo = function(row){
        $scope.row = row;
        $scope.goods = row.details;
        $scope.showFlowDetailsShow = false;
        $scope.showFlowDetailsData = [];
        //$scope.mylabel = $scope.row.otherGoodInShck;
        //判断有没有编辑的权限
        if($scope.row.otherGoodInId && $scope.row.otherGoodInId!==""){
            toaster.getInfo('/a_yongan/single/editpower/'+$scope.row.otherGoodInId,null).then(function(data){
                if(data && data.data){
                    $scope.canEdit = data.data.success;

                }
            });
        }
        $scope.warehouseAdd = !($scope.warehouseAdd);
        $scope.warehouseList = !($scope.warehouseList);
        var isHave = false;
        $scope.rklx.forEach(function(item){
            if(item === $scope.row.otherGoodInRklx){
                isHave = true;
            }
        });
        if(!isHave){
            $scope.rklx.push($scope.row.otherGoodInRklx);
        }
        $scope.rklxlabel = $scope.row.otherGoodInRklx;
        var isHavet = false;
        $scope.lists.forEach(function(item){
            if(item === $scope.row.otherGoodInShck){
                isHavet = true;
            }
        });
        if(!isHavet){
            $scope.lists.push($scope.row.otherGoodInShck);
        }
        $scope.mylabel = $scope.row.otherGoodInShck;
        getAllFile();
    };
    $scope.showSelectCustomer = function(name,lxr,ph){
        var modalInstance = $modal.open({
            templateUrl: 'selectCustomer.html',
            controller: 'selectCustomerCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            $('#'+name+'').val(selectedItem.name);
            $('#'+lxr+'').val(selectedItem.people);
            $('#'+ph+'').val(selectedItem.phone);
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.showSelectGoods = function(obj,index){
        var modalInstance = $modal.open({
            templateUrl: 'selectGoods.html',
            controller: 'selectGoodsCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            objToGo(selectedItem,index);
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.showSelectUser = function(id){
        var modalInstance = $modal.open({
            templateUrl: 'selectUser.html',
            controller: 'selectUserCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            $('#'+id+'').val(selectedItem.name);
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.showFiles = [];
    $scope.upFile=function(){
        var obj = $("#uploadFile")[0];
        var isHaveFile = false;
        $scope.showFiles.forEach(function(item){
            if(item.myFileRealName===obj.files[0].name){
                isHaveFile = true;
            }
        });
        if(isHaveFile){
            showMessage('warning','',"已存在同名文件或重复文件！");
            return false;
        }
        $scope.showFiles.push({
            myFileRealName:obj.files[0].name,
            myFileSize:obj.files[0].size,
            isSuccess:false,
            isCancel:false,
            isError:false,
            isUploading:false,
            progress:0,
            file:obj.files[0]
        });
    };
    $scope.doupFile=function(index){
        uploadFiles(index);
    };

    function makeFileData(data){
        data.forEach(function(item){
            item.progress = 100;
            item.isSuccess = true;
            item.isCancel = true;
            item.isError = false;
            item.isUploading = true;
        });
        $scope.showFiles = data;
    }
    function getAllFile(){
        toaster.getInfo('/a_yongan/file/getallfile/'+$scope.row.otherGoodInDh,null).then(function(data){
            if(data && data.data && data.data.success){
                makeFileData(data.data.data);
            }
        });
    }
    $scope.deleteFile = function (index) {
        if(!$scope.showFiles[index].isUploading){
            $scope.showFiles.splice(index,1);
        }else{
            toaster.getInfo('/a_yongan/file/deletefile/'+$scope.showFiles[index].myFileId,null).then(function(data){
                if(data && data.data && data.data.success){
                    $scope.showFiles.splice(index,1);
                    showMessage('success','','删除成功！');
                }else{
                    showMessage('warning','','删除失败！');
                }
            });
        }
    };
    function uploadFiles(index){
        $scope.showFiles[index].isUploading = true;
        var formData = new FormData();
        //formData.append("file",$("#uploadFile")[0].files[0]);//append()里面的第一个参数file对应permission/upload里面的参数file
        formData.append("file",$scope.showFiles[index].file);
        $.ajax({
            type:"post",
            async:true,  //这里要设置异步上传，才能成功调用myXhr.upload.addEventListener('progress',function(e){}),progress的回掉函数
            Accept:'text/html;charset=UTF-8',
            data:formData,
            //contentType:'multipart/form-data',
            url: '/a_yongan/file/upload/otherwarehousing/'+$scope.row.otherGoodInDh,
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            xhr:function(){
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ // check if upload property exists
                    myXhr.upload.addEventListener('progress',function(e){
                        var loaded = e.loaded;                  //已经上传大小情况
                        var total = e.total;                      //附件总大小
                        var percent = Math.floor(100*loaded/total);     //+"%"已经上传的百分比
                        $scope.showFiles[index].progress = percent;
                        //$("#processBar").css("width",percent);
                    }, false); // for handling the progress of the upload
                }
                return myXhr;
            },
            success:function(data){
                if(data.success){
                    showMessage('success','','上传成功！');
                    $scope.showFiles[index].myFileId = data.error;
                    $scope.showFiles[index].progress = 100;
                    $scope.showFiles[index].isUploading = true;
                    $scope.showFiles[index].isSuccess = true;
                }else{
                    showMessage('warning','',data.error);
                    $scope.showFiles[index].isUploading = false;
                    $scope.showFiles[index].isSuccess = false;
                }
            },
            error:function(){
                showMessage('warning','','上传失败！');
                $scope.showFiles[index].isUploading = false;
                $scope.showFiles[index].isError = true;
            }
        });
    }
    inIt();
    $scope.isPrint = false;
    $scope.myPrintShow = function(){
        $scope.isPrint = !$scope.isPrint;
        $scope.warehouseAdd = !$scope.warehouseAdd;
    };
    $scope.myPrint = function(){
        var input = $('#orderPrint');
        input.print({
            globalStyles:true,
            noPrintSelector:'.no-print'
        });
    };

    $scope.showFlowDetailsShow = false;
    $scope.showFlowDetailsData = [];
    $scope.showFlowDetails = function(){
        if($scope.showFlowDetailsShow){
            $scope.showFlowDetailsShow = false;
        }else{
            $scope.showFlowDetailsShow = true;
            toaster.getInfo('/a_yongan/list/processrecording/'+$scope.row.otherGoodInId,null).then(function(data){
                if(data && data.data && data.data.data){
                    data.data.data.forEach(function(item){
                        item.createTime = $filter("date")(item.createTime, "yyyy-MM-dd HH:mm:ss");
                        if(item.prType==="起草"){
                            item.prFlowToName = "提单";
                            item.prToUser = item.prUser;
                        }
                    })
                    $scope.showFlowDetailsData = data.data.data;
                }
            });
        }
    };
}])
;